import { defineEventHandler, readBody, createError, setCookie } from "h3";
import { UserService } from "../../services/userService";
import { saveToken } from "../../utils/jwt"
import { UserLoginSchema } from '@/schema/user.schema'

export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  // 获取请求体数据
  const result = UserLoginSchema().safeParse(body)
  if (!result.success) {
    // 校验失败，返回错误信息
    throw createError({
      statusCode: 400,
      statusMessage: result.error.name,
      data: result.error.issues,
    })
  }
  const { email, password, rememberMe } = body

  if (!email || !password) {
    throw createError({
      statusCode: 400,
      statusMessage: "Email and password are required",
    });
  }

  const user = await UserService.findByEmail(email);
  if (!user || !user.password) {
    throw createError({
      statusCode: 401,
      statusMessage: "Invalid credentials",
    });
  }

  const isValidPassword = await UserService.verifyPassword(password, user.password);
  if (!isValidPassword) {
    throw createError({
      statusCode: 401,
      statusMessage: "Invalid credentials",
    });
  }
  saveToken(event, user, rememberMe)
  
  return {}
});